/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.viral.struts2;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.List;

/**
 * Connect to Solr and issue a query
 */
public class SolrJExample {

	public static final String[] CATEGORIES = { "a", "b", "c", "d" };
	public String name;
	private ArrayList<SolrJExample> fcts = new ArrayList<SolrJExample>();
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String execute() throws IOException,
			SolrServerException {
		SolrServer server = new CommonsHttpSolrServer(
				"http://localhost:8983/solr/");
		Random rand = new Random();
		// Index some documents
		/*
		 * Collection<SolrInputDocument> docs = new
		 * HashSet<SolrInputDocument>(); for (int i = 0; i < 10; i++) {
		 * SolrInputDocument doc = new SolrInputDocument();
		 * 
		 * //doc.addField("subject", "Subject: " + i); doc.addField("id", " " +
		 * i); doc.addField("description", "This is the " + i +
		 * "(th|nd|rd) piece of content."); System.out.println("Doc[" + i +
		 * "] is " + doc); docs.add(doc); } UpdateResponse response =
		 * server.add(docs); System.out.println("Response: " + response); //Make
		 * the documents available for search server.commit();
		 */
		// create the query
		String variable = null;
		SolrQuery query = new SolrQuery("title:" + variable);
		// indicate we want facets
		query.setFacet(true);
		// indicate what field to facet on
		query.addFacetField("title");

		// we only want facets that have at least one entry
		query.setFacetMinCount(1);

		// query.addFacetQuery("price:[* TO 400]");

		// run the query
		QueryResponse results = server.query(query);
		// System.out.println("Query Results: " + results);
		// print out the facets
		List<FacetField> facets = results.getFacetFields();
		for (FacetField facet : facets) {
			// System.out.println("Facet:" + facet);
			// System.out.println(facet);
			System.out.println("facet count is : " + facet.getValueCount());
			for (int i = 0; i < facet.getValueCount(); i++) {
				SolrJExample sj=new SolrJExample();
				sj.setName(facet.getValues().get(i)+"");
				System.out.println(""+facet.getValues().get(i));
				fcts.add(sj);
			}
		}
		return "success";
	}
}
